package com.zzy;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzy.util.HtmlToFileUtil;
import com.zzy.util.UrlToPdfUtil;

/**
 * Servlet implementation class UrlToPDfServlet
 */
@WebServlet("/UrlToPDfServlet")
public class UrlToPDfServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UrlToPDfServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 String path = request.getContextPath();
		 String htmlBasePath = request.getScheme() + "://"
		               + request.getServerName() + ":"
					   + request.getServerPort()
					   + path + "/";
		 
		 String basePath = request.getSession().getServletContext().getRealPath("/");
		 
		  //目标 html地址
		 String targetUrl = request.getParameter("path");
			if (targetUrl == null || targetUrl.equals("")) {
				return;
			}
		 
		 
		 String htmlFilePathUrl = htmlBasePath+"pd4mlTemp/a.html";
		 String pdfPathUrl = htmlBasePath+"pd4mlTemp/a.pdf";
		 
		 String pdfPath=basePath+"pd4mlTemp"+File.separator+"a.pdf";
		 String htmlFilePath=basePath+"pd4mlTemp"+File.separator+"a.html";
		 
		
		try {
			//utl转化本地文件
			HtmlToFileUtil.ConverHtmlToFile(targetUrl, htmlFilePath);
			String fontPath=basePath+"fonts";
			String htmlDocument=UrlToPdfUtil.readFile(htmlFilePath, "utf-8");
			UrlToPdfUtil.doConversion2(htmlDocument, pdfPath, fontPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PrintWriter  out=response.getWriter();
		out.println("html:"+htmlFilePathUrl);
		out.println("pdf:"+pdfPathUrl);
		
		
	}



	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
